<template>
  <div class="category">
    <div class="container">
      <!-- //面包屑 -->
      <SubBread></SubBread>
      <!-- 筛选区 -->
      <SubFilter @changeFilter="changeFilter"></SubFilter>
      <!-- 排序 -->
      <div class="goods-list">
        <!-- 排序组件 -->
        <SubSort @changeSort="changeSort"></SubSort>
        <!-- 商品列表 -->
        <ul>
          <li v-for="goods in goodsList" :key="goods.id">
            <GoodsItem :goods="goods"></GoodsItem>
          </li>
        </ul>
        <!-- 下拉无线加载组件 -->
        <XtxInfiniteLoading
          v-model:loading="loading"
          :finished="finished"
          @load="load"
        ></XtxInfiniteLoading>
      </div>
    </div>
  </div>
</template>

<script>
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import GoodsItem from './components/goods-item.vue'
import { ref } from 'vue'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
export default {
  name: 'SubCategory',
  components: {
    SubBread,
    SubFilter,
    SubSort,
    GoodsItem
  },
  setup () {
    const loading = ref(false)
    const finished = ref(false)
    const route = useRoute()
    const goodsList = ref([]) // 商品列表
    let reqParams = {
      page: 1,
      pageSize: 20,
      categoryId: route.params.id
    }
    // load事件无限加载功能
    const load = () => {
      findSubCategoryGoods(reqParams).then(({ result }) => {
        goodsList.value = [...goodsList.value, ...result.items]
        reqParams.page++
        if (result.items.length < reqParams.pageSize) {
          finished.value = true
        }
      })
      loading.value = false
    }

    // 排序功能
    const changeSort = (sortParams) => {
      reqParams = {
        ...reqParams,
        ...sortParams
      }
      goodsList.value = []
      reqParams.page = 1
      finished.value = false
      load()
    }

    // 筛选功能
    const changeFilter = (filters) => {
      reqParams = {
        ...reqParams,
        ...filters
      }
      goodsList.value = []
      reqParams.page = 1
      finished.value = false
    }
    return {
      loading,
      finished,
      load,
      goodsList,
      changeSort,
      changeFilter
    }
  }
}
</script>

<style lang="less" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
